// 配置后端接口基础路径
const 线下 = "http://localhost:3100/jeecgboot"
const 线上 = "/api"
const API_BASE_URL = 线上;
// 钉钉配置  http://guxiaodou.gubentang.com/  http://127.0.0.1:8081/index.html

document.addEventListener('DOMContentLoaded', function () {
    // 获取DOM元素
    const mobileMenuBtn = document.querySelector('.mobile-menu-btn');
    const navLinks = document.querySelector('.nav-links');
    const navLinksItems = document.querySelectorAll('.nav-links a');
    const pages = document.querySelectorAll('.page-container');
    const userMenuToggle = document.querySelector('.user-menu-toggle');
    const userMenuList = document.getElementById('user-menu-list');

    // 移动端菜单切换功能
    mobileMenuBtn.addEventListener('click', function () {
        navLinks.classList.toggle('active');

        // 旋转汉堡图标
        const icon = mobileMenuBtn.querySelector('i');
        if (navLinks.classList.contains('active')) {
            icon.classList.remove('fa-bars');
            icon.classList.add('fa-times');
        } else {
            icon.classList.remove('fa-times');
            icon.classList.add('fa-bars');
        }
    });

    // 用户菜单展开/收起
    if (userMenuToggle && userMenuList) {
        userMenuToggle.addEventListener('click', function (e) {
            e.stopPropagation();
            const shown = userMenuList.style.display === 'block';
            userMenuList.style.display = shown ? 'none' : 'block';
        });
        // 点击外部关闭
        document.addEventListener('click', function () {
            userMenuList.style.display = 'none';
        });
        // 阻止菜单内部点击冒泡
        userMenuList.addEventListener('click', function (e) { e.stopPropagation(); });
        // 清除缓存菜单项
        const clearBtn = document.getElementById('refresh-cache-menu');
        if (clearBtn) {
            clearBtn.addEventListener('click', function () {
                try { localStorage.removeItem('gxd_user_center_data'); } catch (e) {}
                alert('已清除缓存，请重新接入小程序');
                userMenuList.style.display = 'none';
            });
        }
    }

    // 导航链接点击事件
    navLinksItems.forEach(link => {
        link.addEventListener('click', function (e) {
            e.preventDefault();

            // 获取目标页面ID
            const targetPageId = this.getAttribute('data-page') + '-page';

            // 移除所有导航链接的active类
            navLinksItems.forEach(item => item.classList.remove('active'));
            // 为当前点击的链接添加active类
            this.classList.add('active');

            // 隐藏所有页面
            pages.forEach(page => page.classList.remove('active'));
            // 显示目标页面
            document.getElementById(targetPageId).classList.add('active');

            // 如果切换到答题页面，确保答题列表已加载
            if (this.getAttribute('data-page') === 'quiz') {
                console.log('切换到答题页面，开始加载答题列表...');
                // 强制重新加载答题列表
                initQuizList();
            }

            // 移动端点击后自动关闭菜单
            if (window.innerWidth <= 768) {
                navLinks.classList.remove('active');
                // 恢复汉堡图标
                const icon = mobileMenuBtn.querySelector('i');
                icon.classList.remove('fa-times');
                icon.classList.add('fa-bars');
            }
            // 如果是投票页面，调用 initVotePage()
            if (targetPageId === "vote-page") {
                initVotePage();
            }
        });
    });

    // 提供通过 hash 精准切页的方法
    function switchToPage (pageKey) {
        if (!pageKey) return;
        // 设置导航激活态
        navLinksItems.forEach(item => item.classList.remove('active'));
        const targetLink = document.querySelector(`.nav-links a[data-page="${pageKey}"]`);
        if (targetLink) targetLink.classList.add('active');
        // 显隐页面容器
        pages.forEach(page => page.classList.remove('active'));
        const targetPage = document.getElementById(pageKey + '-page');
        if (targetPage) targetPage.classList.add('active');
        // 进入积分答题时，确保加载列表
        if (pageKey === 'quiz') {
            initQuizList();
        }
    }

    // 监听 hash 变化
    window.addEventListener('hashchange', function () {
        const pageKey = location.hash.replace('#', '');
        if (pageKey) switchToPage(pageKey);
    });

    // 初次进入时根据 hash 切页（此时事件已绑定）
    const initialPageKey = location.hash.replace('#', '');
    if (initialPageKey) switchToPage(initialPageKey);

    // 窗口大小变化时检查是否需要关闭移动菜单
    window.addEventListener('resize', function () {
        if (window.innerWidth > 768 && navLinks.classList.contains('active')) {
            navLinks.classList.remove('active');
            // 恢复汉堡图标
            const icon = mobileMenuBtn.querySelector('i');
            icon.classList.remove('fa-times');
            icon.classList.add('fa-bars');
        }
    });

    // 标签页切换功能（保持不变）
    const tabButtons = document.querySelectorAll('.tab-button');
    tabButtons.forEach(button => {
        button.addEventListener('click', function () {
            tabButtons.forEach(btn => btn.classList.remove('active'));
            this.classList.add('active');
        });
    });

    // 投票页面的星星点击事件（保持不变）
    const stars = document.querySelectorAll('.vote-rating .fa-star');
    stars.forEach(star => {
        star.addEventListener('click', function () {
            const index = Array.from(this.parentElement.children).indexOf(this);
            this.parentElement.querySelectorAll('.fa-star').forEach((s, i) => {
                if (i <= index) {
                    s.classList.add('fas');
                    s.classList.remove('far');
                } else {
                    s.classList.add('far');
                    s.classList.remove('fas');
                }
            });
        });
    });

    initDingH5RemoteDebug();
    
    // 如果带期数 直接进入投票页面
    const period = new URLSearchParams(location.search).get('period');
    initDingTalkLogin(period);


});

// 绑定刷新缓存按钮：清除本地缓存并提示
document.addEventListener('DOMContentLoaded', function () {
    const btn = document.getElementById('refresh-cache-btn');
    if (!btn) return;
    btn.addEventListener('click', function () {
        try {
            localStorage.removeItem('gxd_user_center_data');
        } catch (e) {}
        alert('已清除缓存，请重新接入小程序');
    });
});

// 点击跳转到积分规则页面
document.getElementById('goto-rules-btn').addEventListener('click', function () {
    const ruleLink = document.querySelector('.nav-links a[data-page="rule"]');
    if (ruleLink) ruleLink.click();
});

let userCenterData = {};

// ============== 用户信息本地缓存 ==============
const USER_CACHE_KEY = 'gxd_user_center_data';
const USER_CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000; // 1 周

function getCachedUserCenterData () {
    try {
        const raw = localStorage.getItem(USER_CACHE_KEY);
        if (!raw) return null;
        const wrapped = JSON.parse(raw);
        if (!wrapped || !wrapped.data || !wrapped.ts) return null;
        if (Date.now() - wrapped.ts > USER_CACHE_TTL_MS) {
            localStorage.removeItem(USER_CACHE_KEY);
            return null;
        }
        return wrapped.data;
    } catch (e) {
        return null;
    }
}

function setCachedUserCenterData (data) {
    try {
        localStorage.setItem(USER_CACHE_KEY, JSON.stringify({ data, ts: Date.now() }));
    } catch (e) {
        // ignore quota or serializing errors
    }
}

function initDingTalkLogin (period) {
    // 尝试读取本地缓存，若存在且未过期，直接使用并跳过网络请求
    // const cached = getCachedUserCenterData();
    const cached = null;
    if (cached) {
        userCenterData = cached;
        window.userCenterData = cached;
        updateUserInfo(cached);
        hideLoading();
        return;
    }
    if (typeof dd === "undefined") {
        console.error("钉钉 JSAPI 未加载");
        hideLoading();
        return;
    }
showLoading(); // <<=== 加在最前
    dd.ready(function () {

        dd.runtime.permission.requestAuthCode({

            corpId: "ding60ca55316ff60640f5bf40eda33b7ba0", // 替换为钉钉管理后台提供的 CorpId
            onSuccess: function (result) {
                const authCode = result.code;
                // alert(API_BASE_URL)
                // 调用后端接口换取用户信息
                // 线下 http://localhost:3100/jeecgboot/dingTalkV2/getUserInfo?code=
                // 线上 /api/dingTalkV2/getUserInfo?code=
                fetch(API_BASE_URL + '/dingTalkV2/getUserInfo?code=' + authCode, {
                    method: 'GET',
                    credentials: 'include'
                })
                    .then(res => res.json())
                    .then(data => {

                         hideLoading(); // <<=== 数据返回后隐藏
                        if (data.success) {
                            userCenterData = data.result;
                            window.userCenterData = data.result;
                            setCachedUserCenterData(data.result);
                            updateUserInfo(data.result);
                            if (period) {
                                // 直接进入详情
                                showPageAndMenu('vote-page');
                                initVotePage(period); // 如果要动态渲染期数下拉
                            } 

                        } else {
                            alert('登录失败：' + data.message);
                        }
                    })
                    .catch(err => {
                         hideLoading(); // <<=== 出错也隐藏
                        console.error('登录请求失败', err);
                    });
            },
            onFail: function (err) {
                  hideLoading(); // <<=== 失败也隐藏
                console.error('获取 authCode 失败：', err);
            }
        });
    });

    dd.error(function (err) {
          hideLoading(); // <<=== 失败也隐藏
        console.error('钉钉 JSAPI 初始化失败：', err);
    });
}

function updateUserInfo (data) {

    // document.querySelector('.user-info .avatar').innerText = data.avatar == '' ? data.name[0] : data.avatar;
    // document.querySelector('.user-info .name').innerText = data.name;
    const avatarEl = document.querySelector('.user-info .avatar');
    const nameEl = document.querySelector('.user-info .name');
    // 设置名字
    nameEl.textContent = data.name;
    // 设置头像
    if (!data.avatar) {
        // 没有头像，用名字首字母
        avatarEl.innerHTML = `<span class="avatar-text">${data.name[0]}</span>`;
    } else {
        // 有头像，显示图片
        avatarEl.innerHTML = `<img src="${data.avatar}" alt="头像" class="avatar-img">`;
    }

    document.querySelector('.monthPoints').innerText = data.monthPoints;
    document.querySelector('.yearPoints').innerText = data.yearPoints;
    document.querySelector('.profile-stat-item .monthPoints').innerText = data.monthPoints;
    document.querySelector('.profile-stat-item .yearPoints').innerText = data.yearPoints;
    document.querySelector('.profile-stat-item .yearlyRank').innerText = data.yearlyRank == null ? '-' : data.yearlyRank;
    document.querySelector('.profile-stat-item .exchangeNumber').innerText = data.exchangeNumber;

    const { topMonth, topQuarter, topYear, records, goods, types } = data;

    if (topMonth) {
        renderRankList(topMonth, 'month-rank-list');
    }
    if (topQuarter) {
        renderRankList(topQuarter, 'quarter-rank-list');
    }
    if (topYear) {
        renderRankList(topYear, 'year-rank-list');
    }
    if (records) {
        renderPointRecords(records, 'integral-record-list');
    }
    if (goods) {
        renderShopItems(goods, 'shop-item-list');
    }
    if (types) {
        renderPointRules(types, 'rule-item-list');
    }

    // 默认加载“积分记录”tab（首页默认显示）
    if (records) {
        renderPointRecords(records, 'points-list');
    }


    // 赋值到全局，方便其他页面（如 quiz.html）通过 window 读取
    try { window.userCenterData = data; } catch (e) {}
    // 可选：更新积分和页面信息
    // document.querySelector('.stat-value').innerText = user.totalPoints;
}


// 个人中心的积分记录 兑换记录 个人信息  切换
document.querySelectorAll('.tab-button').forEach(button => {
    button.addEventListener('click', () => {
        const target = button.getAttribute('data-tab');

        // tab 样式切换
        document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
        button.classList.add('active');

        // tab 内容切换
        document.querySelectorAll('.tab-pane').forEach(tab => tab.style.display = 'none');
        document.getElementById(`${target}-tab`).style.display = 'block';

        // 根据已有数据渲染
        if (target === 'points' && userCenterData.records) {
            renderPointRecords(userCenterData.records, 'points-list');
        } else if (target === 'exchange' && userCenterData.exchanges) {
            renderExchangeRecords(userCenterData.exchanges, 'exchange-list');
        } else if (target === 'info' && userCenterData) {
            renderUserInfo(userCenterData);
        }
    });
});

// 监听积分商城的“立即兑换”按钮点击
document.getElementById('shop-item-list').addEventListener('click', function (e) {
  if (e.target && e.target.matches('button[data-id]')) {
    alert('暂未开放');
  }
});


function renderRankList (rankList, containerId) {
    const ul = document.getElementById(containerId);
    if (!ul) return;
    ul.innerHTML = '';

    rankList.forEach((item, index) => {
        const li = document.createElement('li');
        li.className = 'rank-item';

        const rankDiv = document.createElement('div');
        rankDiv.className = 'rank-number';
        if (index === 0) rankDiv.classList.add('top1');
        else if (index === 1) rankDiv.classList.add('top2');
        else if (index === 2) rankDiv.classList.add('top3');
        rankDiv.textContent = index + 1;

        const nameDiv = document.createElement('div');
        nameDiv.className = 'rank-name';
        nameDiv.textContent = item.name;

        const valueDiv = document.createElement('div');
        valueDiv.className = 'rank-value';
        valueDiv.textContent = item.total_points + '豆';

        li.appendChild(rankDiv);
        li.appendChild(nameDiv);
        li.appendChild(valueDiv);

        ul.appendChild(li);
    });
}

// 首页-积分记录
function renderPointRecords (records, containerId) {
    const ul = document.getElementById(containerId);
    if (!ul) return;
    ul.innerHTML = '';

    records.forEach(item => {
        const li = document.createElement('li');
        li.className = 'integral-item';

        // 左侧信息
        const infoDiv = document.createElement('div');
        infoDiv.className = 'integral-info';

        const nameDiv = document.createElement('div');
        nameDiv.className = 'integral-name';
        nameDiv.textContent = item.project;

        const metaDiv = document.createElement('div');
        metaDiv.className = 'integral-meta';

        const typeSpan = document.createElement('span');
        typeSpan.className = 'point-type';
        typeSpan.textContent = item.category;

        const dateSpan = document.createElement('span');
        dateSpan.className = 'integral-meta-item';
        dateSpan.textContent = item.recordTime;

        metaDiv.appendChild(typeSpan);
        metaDiv.appendChild(dateSpan);

        infoDiv.appendChild(nameDiv);
        infoDiv.appendChild(metaDiv);

        // 右侧分数
        const statsDiv = document.createElement('div');
        statsDiv.className = 'integral-stats';

        const pointDiv = document.createElement('div');
        pointDiv.className = 'integral-stats-item';
        pointDiv.classList.add(item.point >= 0 ? 'point-gain' : 'point-loss');
        pointDiv.textContent = (item.point >= 0 ? '+' : '') + item.point;

        statsDiv.appendChild(pointDiv);

        // 合并到列表项
        li.appendChild(infoDiv);
        li.appendChild(statsDiv);
        ul.appendChild(li);
    });
}


// 个人中心-积分记录
function renderPointRecords1 (records, containerId) {
    const ul = document.getElementById(containerId);
    ul.innerHTML = '';
    records.forEach(item => {
        const li = document.createElement('li');
        li.className = 'integral-item';

        const info = `<div class="integral-info">
      <div class="integral-name">${item.goodsName}</div>
      <div class="integral-meta">
        <span class="point-type">${item.type}</span>
        <span class="integral-meta-item">${item.date}</span>
      </div>
    </div>`;

        const stats = `<div class="integral-stats">
      <div class="integral-stats-item ${item.point >= 0 ? 'point-gain' : 'point-loss'}">
        ${item.point >= 0 ? '+' : ''}${item.point}
      </div>
    </div>`;

        li.innerHTML = info + stats;
        ul.appendChild(li);
    });
}
// 个人中心-兑换记录
function renderExchangeRecords (records, containerId) {
    const ul = document.getElementById(containerId);
    ul.innerHTML = '';
    records.forEach(item => {
        const li = document.createElement('li');
        li.className = 'integral-item';

        const info = `<div class="integral-info">
      <div class="integral-name">${item.goodsName}</div>
      <div class="integral-meta">
        <span class="point-type">兑换记录</span>
        <span class="integral-meta-item">${item.recordTime}</span>
      </div>
    </div>`;

        const stats = `<div class="integral-stats">
      <div class="integral-stats-item point-loss">-${Math.abs(item.point)}</div>
    </div>`;

        li.innerHTML = info + stats;
        ul.appendChild(li);
    });
}


// 个人中心- 个人信息
function renderUserInfo1 (user) {
    const container = document.getElementById('user-info-container');
    container.innerHTML = `
    <p><strong>姓名：</strong>${user.name}</p>
    <p><strong>职位：</strong>${user.title}</p>
    <p><strong>手机号：</strong>${user.mobile}</p>
  `;
}
// 个人中心- 个人信息
function renderUserInfo (user) {
    const container = document.getElementById('user-info-container');
    container.innerHTML = `
    <div class="section-card">
      <div class="section-content">
        <div class="card-title">个人信息</div>
        <div class="info-list">
          <div class="info-item">
            <span class="info-label">姓名：</span>
            <span class="info-value">${user.name || ''}</span>
          </div>
          <div class="info-item">
            <span class="info-label">职位：</span>
            <span class="info-value">${user.title || ''}</span>
          </div>
          <div class="info-item">
            <span class="info-label">手机号：</span>
            <span class="info-value">${user.mobile || ''}</span>
          </div>
        </div>
      </div>
    </div>
  `;
}

// 积分商城
function renderShopItems (items, containerId) {
    const container = document.getElementById(containerId);
    container.innerHTML = '';

    items.forEach(item => {
        const div = document.createElement('div');
        div.className = 'shop-item';
        const imageHtml = item.pic
            ? `<img src="${item.pic}" alt="${item.name}" class="shop-image-icon" />`
            : `<i class="fas fa-gift"></i>`;
        div.innerHTML = `
        <div class="shop-image">
        ${imageHtml}
      </div>
      <div class="shop-info">
        <div class="shop-title">${item.name}</div>
        <div class="shop-meta">
          <div>剩余: ${item.number}件</div>
          <div class="shop-points">${item.point}积分</div>
        </div>
        <button class="btn btn-primary btn-block" data-id="${item.id}" style="display: none;" >立即兑换</button>
      </div>
    `;
        container.appendChild(div);
    });
}

// 积分规则
function renderPointRules (rules, containerId) {
    const container = document.getElementById(containerId);
    container.innerHTML = '';

    const grouped = {};

    // 按类型分组
    rules.forEach(item => {
        const category = item.category || '其他';
        if (!grouped[category]) {
            grouped[category] = [];
        }
        grouped[category].push(item);
    });

    for (const [category, items] of Object.entries(grouped)) {
        const groupDiv = document.createElement('div');
        groupDiv.className = 'point-rule-group';
        groupDiv.innerHTML = `
      <h3 class="rule-group-title">${category}</h3>
      <div class="table-wrapper">
        <table class="rule-table">
            <colgroup>
      <col style="width: 20%;">
      <col style="width: 30%;">
      <col style="width: 30%;">
      <col style="width: 20%;">
    </colgroup>
          <thead>
            <tr>
              <th>项目</th>
              <th>行为标准</th>
              <th>固小豆值</th>
              <th>证明材料</th>
            </tr>
          </thead>
          <tbody>
            ${items.map(row => `
              <tr>
                <td>${row.project}</td>
                <td>${row.behavioralStandards}</td>
                <td>${row.guxiaodouValue}</td>
                <td>${row.supportDocuments}</td>
              </tr>
            `).join('')}
          </tbody>
        </table>
      </div>
    `;
        container.appendChild(groupDiv);
    }
}


// 初始化答题列表
function initQuizList () {
    console.log('开始获取答题列表...');
    const userId = (userCenterData && (userCenterData.userid || userCenterData.userId)) || '';
    const listUrl = API_BASE_URL + '/hr/dtQuestion/titleList?userId=' + encodeURIComponent(userId);
    console.log('请求地址:', listUrl);

    fetch(listUrl, {
        method: 'GET',
        credentials: 'include'
    })
        .then(res => {
            console.log('答题列表响应状态:', res.status);
            return res.json();
        })
        .then(data => {
            console.log('答题列表响应数据:', data);
            if (data.success && data.result && data.result.records) {
                console.log('答题列表数据:', data.result.records);
                renderQuizList(data.result.records);
            } else {
                console.error('获取答题列表失败：', data.message);
                renderQuizList([]); // 渲染空列表
            }
        })
        .catch(err => {
            console.error('请求答题列表失败：', err);
            renderQuizList([]); // 渲染空列表
        });
}

// 渲染答题列表
function renderQuizList (quizList) {
    console.log('开始渲染答题列表，数据:', quizList);

    const container = document.getElementById('quiz-item-list');
    if (!container) {
        console.error('找不到答题列表容器: quiz-item-list');
        return;
    }

    console.log('找到容器:', container);
    container.innerHTML = '';

    if (quizList.length === 0) {
        console.log('答题列表为空，显示空状态');
        container.innerHTML = '<div style="text-align: center; padding: 40px; color: #999;">暂无可用答题</div>';
        return;
    }

    console.log('开始渲染', quizList.length, '个答题项目');

    quizList.forEach((quiz, index) => {
        console.log(`渲染第${index + 1}个答题:`, quiz);

        const div = document.createElement('div');
        div.className = 'quiz-card';

        // 根据时间和enable字段判断状态
        const now = new Date();
        const startTimeDate = new Date(quiz.startTime);
        const endTimeDate = new Date(quiz.endTime);
        // 格式化开始和结束时间，显示到秒（用于提示）
        const startTime = quiz.startTime ? quiz.startTime : '未知';
        const endTime = quiz.endTime ? quiz.endTime : '未知';
        // 是否已作答
        const isAnswered = quiz.isAnswer === 1 || quiz.isAnswer === '1';

        let buttonText = '开始答题';
        let buttonClass = 'btn btn-primary btn-block';
        let isEnabled = false;

        // 优先“已作答”显示
        if (isAnswered) {
            buttonText = '已作答';
            buttonClass = 'btn btn-secondary btn-block';
        } else if (quiz.enable !== '1' && quiz.enable !== 1) {
            buttonText = '暂未开放';
            buttonClass = 'btn btn-secondary btn-block';
        } else if (now < startTimeDate) {
            buttonText = '暂未开放';
            buttonClass = 'btn btn-secondary btn-block';
        } else if (now > endTimeDate) {
            buttonText = '已结束';
            buttonClass = 'btn btn-ended btn-block';
        } else {
            buttonText = '开始答题';
            buttonClass = 'btn btn-primary btn-block';
            isEnabled = true;
        }

        // 为不可用按钮添加提示信息
        let tooltip = '';
        if (!isEnabled) {
            if (isAnswered) {
                tooltip = '您已作答';
            } else if (quiz.enable !== '1' && quiz.enable !== 1) {
                tooltip = '该答题暂未开放';
            } else if (now < startTimeDate) {
                tooltip = `答题将于 ${startTime} 开始`;
            } else if (now > endTimeDate) {
                tooltip = `答题已于 ${endTime} 结束`;
            }
        }

        div.innerHTML = `
            <div class="quiz-title">${quiz.title || '未命名答题'}</div>
            <div class="quiz-meta">
                <div>开始时间: ${startTime}</div>
                <div>结束时间: ${endTime}</div>
                <div>题目数量: ${quiz.total || 0}题</div>
            </div>
            <div class="quiz-points">可获得积分: <span class="point-gain">${quiz.integral || 0}</span></div>
            <button class="${buttonClass}" data-id="${quiz.id}" ${!isEnabled ? 'disabled' : ''} ${tooltip ? `data-tooltip="${tooltip}"` : ''}>
                ${buttonText}
            </button>
        `;

        container.appendChild(div);
        console.log(`第${index + 1}个答题渲染完成`);
    });

    console.log('答题列表渲染完成，共渲染', container.children.length, '个项目');

    // 绑定答题按钮点击事件
    bindQuizButtonEvents();
}

// 绑定答题按钮事件
function bindQuizButtonEvents () {
    const quizButtons = document.querySelectorAll('#quiz-item-list .btn[data-id]');
    quizButtons.forEach(button => {
        button.addEventListener('click', function () {
            const quizId = this.getAttribute('data-id');
            const isEnabled = !this.disabled;
            if (!isEnabled) return;
            // 跳转独立详情页
          // 跳转独立详情页
          const uid = (userCenterData && (userCenterData.userid || userCenterData.userId)) || '';
          const uname = (userCenterData && userCenterData.name) || '';
          let url = 'quiz.html?pid=' + encodeURIComponent(quizId);
          if (uid) url += '&uid=' + encodeURIComponent(uid);
          if (uname) url += '&uname=' + encodeURIComponent(uname);
          window.location.href = url;
        });
    });
}

// 渲染详情页



function renderQuizDetail (questions) {
    const container = document.getElementById('quiz-questions-container');
    if (!container) return;

    container.innerHTML = '';
    const total = questions.length;
    updateQuizProgress(0, total);

    questions.forEach((q, idx) => {
        const isRequired = String(q.required) === '1';
        const options = (q.options || '').split(',').map(s => s.trim()).filter(Boolean);
        const wrapper = document.createElement('div');
        wrapper.className = 'question-item';
        wrapper.setAttribute('data-qid', q.id);
        wrapper.setAttribute('data-type', q.type);
        wrapper.setAttribute('data-required', isRequired ? '1' : '0');

        const titleHtml = `
            <div class="question-title">${idx + 1}. ${q.title || ''}
                ${isRequired ? '<span class="required-mark">*</span>' : ''}
            </div>
        `;

        let optionsHtml = '<div class="options-group">';
        if (q.type === 'radio') {
            options.forEach((opt, i) => {
                const id = `q_${q.id}_${i}`;
                optionsHtml += `
                  <label class="option-item" for="${id}">
                    <input id="${id}" type="radio" name="q_${q.id}" value="${opt}">
                    <span>${opt}</span>
                  </label>`;
            });
        } else if (q.type === 'checkbox') {
            options.forEach((opt, i) => {
                const id = `q_${q.id}_${i}`;
                optionsHtml += `
                  <label class="option-item" for="${id}">
                    <input id="${id}" type="checkbox" name="q_${q.id}" value="${opt}">
                    <span>${opt}</span>
                  </label>`;
            });
        } else {
            // 兜底当做单选
            options.forEach((opt, i) => {
                const id = `q_${q.id}_${i}`;
                optionsHtml += `
                  <label class="option-item" for="${id}">
                    <input id="${id}" type="radio" name="q_${q.id}" value="${opt}">
                    <span>${opt}</span>
                  </label>`;
            });
        }
        optionsHtml += '</div>';

        wrapper.innerHTML = titleHtml + optionsHtml;
        container.appendChild(wrapper);
    });

    // 绑定交互以更新进度
    container.addEventListener('change', onQuizAnswerChange, { once: true });
    container.addEventListener('change', onQuizAnswerChange);

    // 绑定按钮
    const backBtn = document.getElementById('quiz-back-btn');
    if (backBtn) backBtn.onclick = () => showPage('quiz-page');
    const cancelBtn = document.getElementById('quiz-cancel-btn');
    if (cancelBtn) cancelBtn.onclick = () => showPage('quiz-page');
    const submitBtn = document.getElementById('quiz-submit-btn');
    if (submitBtn) submitBtn.onclick = validateAndSubmitQuiz;
}

function onQuizAnswerChange () {
    const container = document.getElementById('quiz-questions-container');
    if (!container) return;
    const items = Array.from(container.querySelectorAll('.question-item'));
    const total = items.length;
    const answered = items.reduce((acc, item) => {
        const type = item.getAttribute('data-type');
        const qid = item.getAttribute('data-qid');
        if (type === 'checkbox') {
            const checked = container.querySelectorAll(`input[name="q_${qid}"]:checked`).length;
            return acc + (checked > 0 ? 1 : 0);
        }
        const checked = container.querySelectorAll(`input[name="q_${qid}"]:checked`).length;
        return acc + (checked > 0 ? 1 : 0);
    }, 0);
    updateQuizProgress(answered, total);
}

function updateQuizProgress (answered, total) {
    const bar = document.getElementById('quiz-progress-bar');
    const text = document.getElementById('quiz-progress-text');
    const pct = total === 0 ? 0 : Math.round((answered / total) * 100);
    if (bar) bar.style.width = pct + '%';
    if (text) text.textContent = `${answered}/${total}`;
}

// 校验并提交（占位）
function validateAndSubmitQuiz () {
    const container = document.getElementById('quiz-questions-container');
    const items = Array.from(container.querySelectorAll('.question-item'));
    for (const item of items) {
        const required = item.getAttribute('data-required') === '1';
        if (!required) continue;
        const qid = item.getAttribute('data-qid');
        const checked = container.querySelectorAll(`input[name="q_${qid}"]:checked`).length;
        if (checked === 0) {
            item.scrollIntoView({ behavior: 'smooth', block: 'center' });
            item.style.boxShadow = '0 0 0 2px rgba(255,77,79,0.3)';
            setTimeout(() => { item.style.boxShadow = 'none'; }, 1500);
            alert('请完成所有必填题');
            return;
        }
    }
    alert('提交功能暂未接入后端，稍后可打通接口。');
}

function showPage (pageId) {
    const pages = document.querySelectorAll('.page-container');
    pages.forEach(p => p.classList.remove('active'));
    pages.forEach(p => p.style.display = 'none');
    const target = document.getElementById(pageId);
    if (target) {
        target.style.display = 'block';
        target.classList.add('active');
    }
}
function showPageAndMenu(pageId) {
    // 1. 隐藏所有页面
    document.querySelectorAll('.page-container').forEach(p => p.classList.remove('active'));
    // 2. 显示目标页面
    const page = document.getElementById(pageId);
    if (page) page.classList.add('active');

    // 3. 同步菜单高亮
    document.querySelectorAll('.nav-links a').forEach(a => a.classList.remove('active'));

    // menu data-page 与 pageId 对应
    let menuPage = pageId.replace('-page', ''); // vote-page -> vote
    const menuItem = document.querySelector(`.nav-links a[data-page="${menuPage}"]`);
    if (menuItem) menuItem.classList.add('active');
}


// 覆盖加载遮罩函数，保证在不存在遮罩节点时也不会报错
function showLoading () {
    const el = document.getElementById('loading-overlay');
    if (el) el.style.display = 'flex';
}
function hideLoading () {
    const el = document.getElementById('loading-overlay');
    if (el) el.style.display = 'none';
}



// ===================投票相关===========================

// 渲染期数下拉（从后台获取）
function renderPeriodSelect(period) {
    const select = document.getElementById("periodSelect");
    select.innerHTML = "";

    fetch(API_BASE_URL + `/hr/gbtIntegralVoteInfo/periods`)
        .then(res => res.json())
        .then(data => {
            if (!data.success || !data.result || data.result.length === 0) {
                console.warn("未获取到期数数据");
                return;
            }

            const periods = data.result;

            periods.forEach((value, index) => {
                const option = document.createElement("option");
                option.value = value;
                option.textContent = value;
                  // 如果传入 period 并匹配，则选中；否则第一个选中
                if (period && value === period) {
                    option.selected = true;
                } else if (!period && index === 0) {
                    option.selected = true;
                }
                select.appendChild(option);
            });

            // 默认加载投票选项
            const selectedPeriod = period && periods.includes(period) ? period : periods[0];
            loadVoteOptions(selectedPeriod);
            

        })
        .catch(err => {
            console.error("加载期数失败:", err);
        });
}


// 拉取投票选项
function loadVoteOptions (period) {
    
    fetch(API_BASE_URL + `/hr/gbtIntegralVoteInfo/getVoteInfoByPeriod?userid=${userCenterData.userid}&period=${period}`)
        .then(res => res.json())
        .then(data => {

            const options = data.result;
            renderVoteOptions(options); 

        })
        .catch(err => console.error("加载投票选项失败:", err));

}

// 渲染投票选项
function renderVoteOptions (options) {


     const description = document.getElementById("description");
     description.textContent = options.description;
     const mostdiv = document.getElementById("most");
     mostdiv.textContent = `本期投票最多可投 ${options.most} 票！`;

    const container = document.getElementById("voteOptions");
    container.innerHTML = "";

    const records = options.voteList || [];
    const most = options.most;
    const isVoteInfo = options.isVote;
    const endTime = options.endTime ? new Date(options.endTime) : null;
    const now = new Date();

    records.forEach(opt => {
        const item = document.createElement("div");
        item.className = "vote-item";
        item.innerHTML = `
          <label>
            <input type="checkbox" name="voteOption" value="${opt.id}">
            <span class="vote-type">${opt.voteTypeStr}</span>： 
            <span class="vote-reason">${opt.reason}</span>
          </label>
          <div class="vote-count">
            票数: ${opt.votes} 占比: ${opt.percent}
          </div>
        `;

        const input = item.querySelector("input");

        // 已投票：禁用，勾选用户已选中的
        if (isVoteInfo) {
            input.disabled = true;
            if (opt.isVote) {
                input.checked = true;
            }
        }

        container.appendChild(item);
    });

    // 限制多选最多 most 个
    const checkboxes = container.querySelectorAll("input[type=checkbox]");
    checkboxes.forEach(cb => {
        cb.addEventListener("change", () => {
            const checked = container.querySelectorAll("input[type=checkbox]:checked");
            if (checked.length > most) {
                cb.checked = false;
                alert(`本期投票最多可选 ${most} 个`);
            }
        });
    });

    // 更新按钮状态
    const btn = document.getElementById("voteSubmit");
    // alert(isVoteInfo)
    if (isVoteInfo) {
        btn.textContent = "已投票";
        btn.disabled = true;
    } else if (endTime && now > endTime) {
        btn.textContent = "投票已截止";
        btn.disabled = true;
    } else {
        btn.textContent = "提交投票";
        btn.disabled = false;
    }
}



// 提交投票
function submitVote () {
    const checked = document.querySelectorAll("input[name='voteOption']:checked");
    if (!checked || checked.length === 0) {
        alert("请至少选择一个投票项！");
        return;
    }
    const voteIds = Array.from(checked).map(cb => cb.value);

    const period = document.getElementById("periodSelect").value;

    const confirmMsg = `提交后不可更改！\n您确认要提交选中的 ${voteIds.length} 个投票项吗？`;
    if (!confirm(confirmMsg)) {
        return; // 用户取消提交
    }

    fetch(API_BASE_URL + `/hr/gbtIntegralVoteRecord/addRecords`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
            userid: userCenterData.userid,
            period: period,
            voteIds: voteIds
        })
    })
        .then(res => res.json())
        .then(res => {
            if (res.success) {
                alert("投票成功！");
                initVotePage()
            } else {
                alert(res.message || "投票失败");
            }
        });
}

// 初始化投票页
function initVotePage (period) {
    const periodSelect = document.getElementById("periodSelect");
    renderPeriodSelect(period);
    
    // 用 change 事件，只在用户切换时调用
    periodSelect.addEventListener("change", () => {
        loadVoteOptions(periodSelect.value);
    });


    document.getElementById("voteSubmit").addEventListener("click", submitVote);
    // 显示/隐藏 投票委员会提示
    const vipNotice = document.getElementById("vipNotice");
    if (userCenterData.isVip === "Y") {
        vipNotice.style.display = "block";
        vipNotice.textContent = `您是投票委员会的成员，权重为 ${userCenterData.priority}！`;
    } else {
        vipNotice.style.display = "none";
    }
}
